
package org.cjstudio.holypoopsgrs.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.cjstudio.holypoopsgrs.model.UserProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("userProfileRepository")
@Scope("singleton")
public class UserProfileRepository implements Repository<UserProfile> {

	@Autowired
	private PersistenceManagerFactory pmf;

	public void create(UserProfile userProfile) {
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.makePersistent(userProfile);
		} finally {
			pm.close();
		}
	}

	public UserProfile retrieve(String uuid) {
		PersistenceManager pm = pmf.getPersistenceManager();
		UserProfile userProfile, detached = null;
		try {
			userProfile = pm.getObjectById(UserProfile.class, uuid);
			detached = pm.detachCopy(userProfile);
		} catch(Exception e) {
			detached = null;
		} finally {
			pm.close();
		}
		return detached;
	}

	public List<UserProfile> retrieveAll() {
		List<UserProfile> result = null;
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			List<UserProfile> messages = new ArrayList<UserProfile>();
			Extent<UserProfile> extent = pm.getExtent(UserProfile.class, false);
			for (UserProfile userProfile : extent) {
				messages.add(userProfile);
			}
			extent.closeAll();

			result = messages;

			if(result.size() == 0) {
				result = null;
			}
		} catch(Exception e) {

		} finally {
			pm.close();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<UserProfile> retrieveWithRange(int start, int end) {
		PersistenceManager pm = pmf.getPersistenceManager();

		Query query = pm.newQuery(UserProfile.class);
		query.setOrdering("highest desc, highestDate desc");
		query.setRange(start-1, end);

		return (List<UserProfile>) query.execute();
	}

	public void update(UserProfile userProfile) {
		delete(userProfile);
		create(userProfile);

		//but change this...
	}

	public UpdateParams<UserProfile> update(String udid) {
		UpdateParams<UserProfile> params = new UpdateParams<UserProfile>();
		params.pm = pmf.getPersistenceManager();
		try {
			params.obj = params.pm.getObjectById(UserProfile.class, udid);
		} catch(Exception e) {
			return null;
		}
		return params;
	}


	public boolean delete(UserProfile userProfile) {
		return delete(userProfile.udid);
	}

	public boolean delete(String udid) {
		boolean result = true;
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.deletePersistent(pm.getObjectById(UserProfile.class, udid));
		} catch(Exception e) {
			result = false;
		} finally {
			pm.close();
		}
		return result;
	}

}
